package com.by.flutter_init

import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import android.util.Log

class MainActivity : FlutterActivity() {
    
    private val CHANNEL = "wechat_share"
    private val TAG = "MainActivity"
    
    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        
        // 注册高德定位插件
        flutterEngine.plugins.add(AmapLocationPlugin())
        
        // 注册高德地图Platform View
        flutterEngine.platformViewsController.registry.registerViewFactory(
            MapViewFactory.VIEW_TYPE,
            MapViewFactory(flutterEngine.dartExecutor.binaryMessenger)
        )
        
        // ✅ 移除这里的微信SDK初始化，改为在用户同意隐私协议后通过Method Channel调用
        // WeChatShareHelper.initWeChatAPI(this)
        
        // 🔥 注册微信分享Method Channel
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
            when (call.method) {
                // 🔥 新增：初始化微信SDK（由Flutter端在用户同意隐私协议后调用）
                "initWeChat" -> {
                    try {
                        Log.d(TAG, "📞 收到初始化微信SDK请求")
                        val success = WeChatShareHelper.initWeChatAPI(this)
                        if (success) {
                            Log.d(TAG, "✅ 微信SDK初始化成功")
                            result.success(true)
                        } else {
                            Log.e(TAG, "❌ 微信SDK初始化失败")
                            result.error("INIT_FAILED", "微信SDK初始化失败", null)
                        }
                    } catch (e: Exception) {
                        Log.e(TAG, "💥 初始化微信SDK异常: ${e.message}")
                        result.error("EXCEPTION", e.message, null)
                    }
                }
                "shareToWeChat" -> {
                    try {
                        val title = call.argument<String>("title") ?: ""
                        val description = call.argument<String>("description") ?: ""
                        val webUrl = call.argument<String>("webUrl") ?: ""
                        val thumbUrl = call.argument<String?>("thumbUrl")
                        val isTimeline = call.argument<Boolean>("isTimeline") ?: false
                        
                        Log.d(TAG, "💬 收到微信分享请求")
                        Log.d(TAG, "📝 标题: $title")
                        Log.d(TAG, "🌐 链接: $webUrl")
                        Log.d(TAG, "📍 场景: ${if (isTimeline) "朋友圈" else "好友"}")
                        
                        // 检查微信是否安装
                        if (!WeChatShareHelper.isWeChatInstalled()) {
                            Log.w(TAG, "⚠️ 微信未安装")
                            result.error("WECHAT_NOT_INSTALLED", "微信未安装", null)
                            return@setMethodCallHandler
                        }
                        
                        val success = WeChatShareHelper.shareToWeChat(
                            title, description, webUrl, thumbUrl, isTimeline
                        )
                        
                        if (success) {
                            Log.d(TAG, "✅ 微信分享流程启动成功")
                            result.success(true)
                        } else {
                            Log.e(TAG, "❌ 微信分享流程启动失败")
                            result.error("SHARE_FAILED", "分享失败", null)
                        }
                    } catch (e: Exception) {
                        Log.e(TAG, "💥 微信分享异常: ${e.message}")
                        result.error("EXCEPTION", e.message, null)
                    }
                }
                "isWeChatInstalled" -> {
                    try {
                        val installed = WeChatShareHelper.isWeChatInstalled()
                        result.success(installed)
                    } catch (e: Exception) {
                        Log.e(TAG, "💥 检查微信安装状态异常: ${e.message}")
                        result.error("EXCEPTION", e.message, null)
                    }
                }
                else -> {
                    result.notImplemented()
                }
            }
        }
    }
}
